package org.catpay.modules.app.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.catpay.common.utils.CommonMap;
import org.catpay.common.utils.R;
import org.catpay.modules.app.annotation.Login;
import org.catpay.modules.app.annotation.LoginUser;
import org.catpay.modules.app.em.TypeGetIncomeEnum;
import org.catpay.modules.app.entity.IncomeDataEntity;
import org.catpay.modules.app.entity.UserEntity;
import org.catpay.modules.app.entity.WithdrawalDataEntity;
import org.catpay.modules.app.service.AccService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.qiniu.util.Md5;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/app")
@Api(value = "账户controller", tags = { "账户操作接口" })
@Slf4j
public class AppAccountController {
	@Autowired
	AccService accService;

	@Login
	@PostMapping("income/getUserIncomeList")
	@ApiOperation("获取收益信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "type", value = "type,day获取最近7天，month获取最近一个月，times获取时间段内", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "startTime", value = "开始", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "endTime", value = "结束", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "pageNo", value = "页", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "码", required = false, dataType = "String", paramType = "query") })

	public R<?> getUserIncomeData(@LoginUser @ApiIgnore UserEntity user, HttpServletRequest request,
			HttpServletResponse response) {
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		String pageNo = StrUtil.blankToDefault(request.getParameter("pageNo"), "0");
		String pageSzie = StrUtil.blankToDefault(request.getParameter("pageSize"), "20");
		String type = request.getParameter("type");
		Assert.hasLength(type, "type不能为空");
		List<IncomeDataEntity> l = null;
		BigDecimal income = BigDecimal.ZERO;

		// day 返回最近7天的明细 month 返回最近1个月 明细 times 时间段
		switch (TypeGetIncomeEnum.getTypeGetIncomeEnum(type)) {
		case day:
			l = accService.getUserIncomeData(user.getId(), DateUtil.lastWeek().toString(), DateUtil.date().toString(),
					pageNo, pageSzie);
			income = accService.getUserIncome(user.getId(), DateUtil.lastWeek().toString(), DateUtil.date().toString());
			break;
		case month:
			l = accService.getUserIncomeData(user.getId(), DateUtil.lastMonth().toString(), DateUtil.date().toString(),
					pageNo, pageSzie);
			income = accService.getUserIncome(user.getId(), DateUtil.lastMonth().toString(),
					DateUtil.date().toString());
			break;
		case times:
			l = accService.getUserIncomeData(user.getId(), DateUtil.parse(startTime).toString(),
					DateUtil.parse(endTime).toString(), pageNo, pageSzie);
			income = accService.getUserIncome(user.getId(), DateUtil.parse(startTime).toString(),
					DateUtil.parse(endTime).toString());
			break;
		}

		if (income == null)
			income = new BigDecimal(0.00);
		return R.ok(CommonMap.getMap().put("userIncomeList", l).put("allIncome", user.getProfitBalance()).put("income",
				income));
	}

	@Login
	@PostMapping("income/getUserIncomeData")
	@ApiOperation("获取最近收入和(今天和昨天和总计)")
	/**
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @return 返回最近2天收益总和
	 */

	public R<?> getUserIncome(@LoginUser @ApiIgnore UserEntity user, HttpServletRequest request,
			HttpServletResponse response) {

		BigDecimal todayIncome = accService.getUserIncome(user.getId(), DateUtil.date().toDateStr() + " 00:00:00",
				DateUtil.date().toDateStr() + " 23:59:59");
		BigDecimal yesterdayIncome = accService.getUserIncome(user.getId(),
				DateUtil.yesterday().toDateStr() + " 00:00:00", DateUtil.yesterday().toDateStr() + " 23:59:59");
		if (todayIncome == null)
			todayIncome = new BigDecimal(0.00);
		if (yesterdayIncome == null)
			yesterdayIncome = new BigDecimal(0.00);
		return R.ok(CommonMap.getMap().put("todayIncome", todayIncome).put("allIncome", user.getProfitBalance())
				.put("yesterdayIncome", yesterdayIncome));
	}

	@Login
	@PostMapping("income/withdraw")
	@ApiOperation("提现")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "amount", value = "提现金额", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "aliId", value = "支付宝账号", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "name", value = "支付宝姓名", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "password", value = "账号密码", required = true, dataType = "String", paramType = "query")

	})
	public R<?> withdraw(@LoginUser @ApiIgnore UserEntity user, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String amount = request.getParameter("amount");
		String aliId = request.getParameter("aliId");
		String name = request.getParameter("name"); // 支付宝收款人姓名
		String password = request.getParameter("password");
		// String sign = request.getParameter("sign");

		Assert.hasLength(amount, "amount不能为空");
		Assert.hasLength(aliId, "aliId不能为空");
		Assert.hasLength(name, "name不能为空");
		Assert.hasLength(password, "password不能为空");

		// Assert.hasLength(sign, "sign不能为空");

		accService.withdraw(user, amount, aliId, name, password);
		return R.ok();
	}

	@Login
	@PostMapping("income/getWithdrawList")
	@ApiOperation("提现记录")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "pageNo", value = "页", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "码", required = false, dataType = "String", paramType = "query") })
	public R<?> getWithdrawData(@LoginUser @ApiIgnore UserEntity user, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String pageNo = StrUtil.blankToDefault(request.getParameter("pageNo"), "0");
		String pageSzie = StrUtil.blankToDefault(request.getParameter("pageSize"), "20");
		List<WithdrawalDataEntity> l = accService.getWithdrawalData(user.getId(), pageNo, pageSzie);
		return R.ok(CommonMap.getMap().put("withdrawList", l));
	}

	/**
	 * 签名算法
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	private String getSign(Map<String, String> paramMap) throws Exception {
		SortedMap<String, String> smap = new TreeMap<String, String>(paramMap);

		StringBuffer stringBuffer = new StringBuffer();
		for (Map.Entry<String, String> m : smap.entrySet()) {
			String value = m.getValue();
			if (StringUtils.isNotEmpty(value)) {
				stringBuffer.append(m.getKey()).append("=").append(value).append("&");
			}
		}

		String argPreSign = stringBuffer.append("key=VzNCwHYKWanYvPQFS7U7CPePBeDWsUl7").toString();
		String signStr = Md5.md5(argPreSign.getBytes("utf-8")).toUpperCase();
		log.info("签名结果：" + signStr);
		return signStr;
	}

}
